package com.cn.test.record;

import java.util.Arrays;

/**
 * description:
 *
 * @author twj
 * @date 2021/9/9 10:22 .
 */
public class OperateArray {

    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4, 5, 6, 7};
        int[] arr2 = {-1, -100, 3, 99};
        testrotate(arr2);
    }

    private static void testrotate(int[] arr1) {
        System.out.println("--before->" + Arrays.toString(arr1));
        long start = System.currentTimeMillis();
        rotate(arr1, 2);
        long end = System.currentTimeMillis();
        System.out.println("--after->" + Arrays.toString(arr1));

        System.out.println("--------------------------耗时--------------------------------" + (end - start) + "ms----------------------------------------------------");
    }

    /**
     * https://leetcode-cn.com/problems/rotate-array
     * 给定一个数组，将数组中的元素向右移动 k 个位置，其中 k 是非负数。
     * <p>
     * 输入: nums = [1,2,3,4,5,6,7], k = 3
     * 输出: [5,6,7,1,2,3,4]
     * 解释:
     * 向右旋转 1 步: [7,1,2,3,4,5,6]
     * 向右旋转 2 步: [6,7,1,2,3,4,5]
     * 向右旋转 3 步: [5,6,7,1,2,3,4]
     * <p>
     * 输入：nums = [-1,-100,3,99], k = 2
     * 输出：[3,99,-1,-100]
     * 解释:
     * 向右旋转 1 步: [99,-1,-100,3]
     * 向右旋转 2 步: [3,99,-1,-100]
     * <p>
     * 提示：
     * <p>
     * 1 <= nums.length <= 2 * 104
     * -231 <= nums[i] <= 231 - 1
     * 0 <= k <= 105
     *
     * @createby twj on 2021/9/9 10:44
     */
    static void rotate(int[] nums, int k) {
//        int length = nums.length;
//        int[] n = new int[length];
//        for (int i = 0; i < k; i++) {
//            int index = (i + k) % length;
//            n[index]=nums[i];
//        }
//        for (int i = 0; i < length; i++) {
//            nums[i] = n[i];
//        }

//        方法2
        k %= nums.length;
        reverse(nums,0,nums.length-1);
        reverse(nums,0,k-1);
        reverse(nums,k,nums.length-1);


    }


    static void reverse(int nums[],int start,int end){
        while (start<end) {
            int temp =nums[start];
            nums[start] = nums[end];
            nums[end]= temp;
            start++;
            end--;
        }
    }
}
